package admin.web.handler;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import admin.common.enums.ResponseEnum;
import admin.common.vo.ResponseVO;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.stream.Collectors;

@Slf4j
//@RestControllerAdvice(basePackages = {"admin.user.controller","admin.grpc.client.controller"})
public class GlobalExceptionHandler {
    /**
     * 捕捉请求体参数异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class, BindException.class})
    @ResponseBody
    public ResponseVO<Void> handleMethodArgumentNotValidException(HttpServletRequest request,
                                                                  BindException e) {
        log.error("MethodArgumentNotValidException,url={},err={}", request.getRequestURI(), e);
        BindingResult bindingResult = e.getBindingResult();
        StringBuilder sb = new StringBuilder();
        if(CollectionUtil.isNotEmpty(bindingResult.getFieldErrors())){
            sb.append(StringUtils.join(bindingResult.getFieldErrors().stream().map(FieldError::getDefaultMessage).collect(Collectors.toList()), ","));
        }
        String msg = sb.toString();
        return ResponseVO.error(msg);
    }

    /**
     * 捕捉请求参数异常
     * @param request
     * @param e
     * @return
     */
    @ExceptionHandler({ConstraintViolationException.class})
    @ResponseBody
    public ResponseVO<Void> handleConstraintViolationException(HttpServletRequest request,
                                                               ConstraintViolationException e) {
        log.error("FundException,url={},err={}", request.getRequestURI(), e);
        String errMsg = e.getConstraintViolations().stream()
                .map((cv) -> cv == null ? "null" : cv.getMessage())
                .collect(Collectors.joining("\n"));
        return ResponseVO.error(ResponseEnum.ILLEGAL_ARGUMENT_MSG.getCode()
                ,ResponseEnum.ILLEGAL_ARGUMENT_MSG.getMsg());
    }



    /**
     * 全局异常处理
     *
     * @param e
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ResponseVO<Void> handlerException(HttpServletRequest request, Exception e) {
        log.error("Exception,url={}", request.getRequestURI(), e);
        return ResponseVO.error(e.getMessage());
    }
}
